import { NextRequest, NextResponse } from 'next/server'
import { projectQueries, userProjectLinkQueries, todoQueries } from '@/lib/database-prisma'
import { getUserFromRequest } from '@/lib/auth-utils'
import type { Project } from '@/types/database'

interface TodoWithStatus {
  status: '待完成' | '进行中' | '待测试' | '已完成'
  [key: string]: any
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const { projectId } = await params
    const projectIdNum = parseInt(projectId)
    
    const project = await projectQueries.findById.get(projectIdNum)
    
    if (!project) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 })
    }

    const hasAccess = await userProjectLinkQueries.checkUserInProject.get(userInfo.id, project.id)
    if (!hasAccess || hasAccess.count === 0) {
      return NextResponse.json({ error: '您没有访问此项目的权限' }, { status: 403 })
    }
    
    // 获取项目的所有todos
    const todos = await todoQueries.getAllByProjectId.all(project.id)
    
    // 计算各状态的统计数据
    const stats = {
      total: todos.length,
      待完成: todos.filter(todo => todo.status === '待完成').length,
      进行中: todos.filter(todo => todo.status === '进行中').length,
      待测试: todos.filter(todo => todo.status === '待测试').length,
      已完成: todos.filter(todo => todo.status === '已完成').length,
    }

    // 计算完成率
    const completionRate = stats.total > 0 ? Math.round((stats.已完成 / stats.total) * 100) : 0
    
    return NextResponse.json({
      ...stats,
      completionRate,
      projectId: project.id,
      projectName: project.name
    })
  } catch (error) {
    console.error('获取项目统计失败:', error)
    return NextResponse.json({ error: '获取项目统计失败' }, { status: 500 })
  }
} 